package previous.Test_0309;


import java.util.*;

/**
 * Created with Intellij IDEA
 * Description:
 * User: 星辰
 */
 class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
  }
public class Solution {
    //二叉树的最大宽度
    public int widthOfBinaryTree(TreeNode root) {
      if(root==null) return 0;
        Queue<TreeNode> nodeQueue=new LinkedList<>();
        Queue<Integer> indexQueue=new LinkedList<>();
        nodeQueue.offer(root);
        indexQueue.offer(1);
        int ret=0;
        while(!nodeQueue.isEmpty()){
            int size=nodeQueue.size();
            List<Integer> n=new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode node=nodeQueue.poll();
                int index=indexQueue.poll();
                n.add(index);
                if(node.left!=null){
                    nodeQueue.offer(node.left);
                    indexQueue.offer(index*2);
                }
                if(node.right!=null){
                    nodeQueue.offer(node.right);
                    indexQueue.offer(index*2+1);
                }
            }
            ret=Math.max(ret,n.get(n.size()-1)-n.get(0)+1);
        }
        return ret;
    }
    //在每个树行中寻找最大值
    public List<Integer> largestValues(TreeNode root) {
          Queue<TreeNode> queue=new LinkedList<>();
          List<Integer> max=new ArrayList<>();
          if(root==null) return null;
          int m= root.val;
          queue.offer(root);
          while(!queue.isEmpty()){
               int size=queue.size();
              List<Integer> ret=new ArrayList<>();
              m=Integer.MIN_VALUE;
              for (int i = 0; i < size; i++) {
                  TreeNode t=queue.poll();
                  ret.add(t.val);
                  m=Math.max(m,t.val);
                if(t.left!=null) queue.add(t.left);
                if(t.right!=null) queue.add(t.right);
              }
              max.add(m);
          }
         return max;
    }
}
